package me.android.library.common.viewmodel;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

// 通用 ViewModel 工厂
public class GenericViewModelFactory implements ViewModelProvider.Factory {
    private final Object[] params;

    public GenericViewModelFactory(Object... params) {
        this.params = params;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        try {
            // 根据构造函数参数数量和类型创建实例
            if (params == null || params.length == 0) {
                return modelClass.getDeclaredConstructor().newInstance();
            } else {
                Class<?>[] paramTypes = new Class[params.length];
                for (int i = 0; i < params.length; i++) {
                    paramTypes[i] = params[i].getClass();
                }
                return modelClass.getDeclaredConstructor(paramTypes).newInstance(params);
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to create ViewModel", e);
        }
    }
}
